import { useEffect, useState } from "react";
import { createData, actionType } from "./components/createData";

type countTyle = { count: number };
const reducer = (
  state: countTyle,
  action: actionType<countTyle>
): countTyle => {
  switch (action.type) {
    case "ADD_COUNT":
      return {
        count: ++state.count,
      };
    case "CHANGE_COUNT":
      return action.payload;
    default:
      return state;
  }
};
const initData = {
  count: 0,
};
const { subscribe, getData, setDataByAction } = createData<countTyle>(
  initData,
  reducer
);
function index() {
  return (
    <>
      <ChildA />
      <ChildB />
    </>
  );
}
const ChildA = () => {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    subscribe(() => {
      const data: { count: number } = getData();
      setCount(() => data.count);
    });
  }, []);
  return <h2>我是childA组件{count}</h2>;
};

const ChildB = () => {
  const handleAdd = () => {
    const action: actionType<countTyle> = {
      type: "ADD_COUNT",
      payload: {
        count: 0,
      },
    };
    setDataByAction(action);
  };
  const handleInit = () => {
    const action: actionType<countTyle> = {
      type: "CHANGE_COUNT",
      payload: {
        count: 520,
      },
    };
    setDataByAction(action);
  };
  return (
    <>
      <button onClick={handleAdd}>点击++</button>
      <button onClick={handleInit}>点击重制</button>
    </>
  );
};

export default index;
